import fs from 'fs-extra';
import type { Manifest } from 'webextension-polyfill';
import type PkgType from '../package.json';
import { isDev, port, r } from '../scripts/utils';

export async function getManifest() {
  const pkg = (await fs.readJSON(r('package.json'))) as typeof PkgType;

  // update this file to update this manifest.json
  // can also be conditional based on your need
  const manifest: Manifest.WebExtensionManifest = {
    manifest_version: 2,
    name: pkg.displayName || pkg.name,
    version: pkg.version,
    description: pkg.description,

    // 指定扩展的图标放在 Chrome 工具栏中，它定义了扩展图标文件位置，用来做登录
    browser_action: {
      default_icon: './assets/icon-288.png',
      default_popup: './dist/popup/index.html',
    },

    // 定义了扩展的设置页面，配置后在扩展图标点击右键可以看到 选项，点击即打开指定页面。
    options_ui: {
      page: './dist/options/index.html',
      open_in_tab: true,
      chrome_style: false,
    },

    // background 可以使扩展常驻后台，比较常用的是指定子属性 scripts，
    // 表示在扩展启动时自动创建一个包含所有指定脚本的页面。
    background: {
      page: './dist/background/index.html',
      persistent: false,
    },
    icons: {
      16: './assets/icon-288.png',
      48: './assets/icon-288.png',
      128: './assets/icon-288.png',
    },
    // 定义了扩展需要向 Chrome 申请的权限
    permissions: [
      'tabs',
      'storage',
      'activeTab',
      'background',
      'https://juejin.cn/*',
      'http://106.75.82.241:10025/*',
      'https://rd6.zhaopin.com/resume/*',
      `https://ehire.51job.com/*`,
      'https://hr-ma.test.hrtiger.cn/*',
      `https://lpt.liepin.com/cvview/*`,
      `https://h.liepin.com/resume/*`,
      `https://www.zhipin.com/web/boss/*`,
    ],
    // 'http://*/', 'https://*/'

    content_scripts: [
      {
        // run_at: 'document_start',
        include_globs: [
          'https://juejin.cn/*',
          'https://rd6.zhaopin.com/resume/*',
          `https://ehire.51job.com/*`,
          `https://lpt.liepin.com/cvview/*`,
          `https://h.liepin.com/resume/*`,
          `https://www.zhipin.com/web/boss/*`,
        ],
        matches: ['http://*/*', 'https://*/*'],
        js: ['./dist/contentScripts/index.global.js'],
      },
    ],
    web_accessible_resources: ['dist/contentScripts/style.css'],
  };

  if (isDev) {
    // for content script, as browsers will cache them for each reload,
    // we use a background script to always inject the latest version
    // see src/background/contentScriptHMR.ts
    delete manifest.content_scripts;
    manifest.permissions?.push('webNavigation');

    // this is required on dev for Vite script to load
    manifest.content_security_policy = `script-src \'self\' http://localhost:${port}; object-src \'self\'`;
  }

  return manifest;
}
